package com.javatip.project.deep_learning.predict.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.sql.Timestamp;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import com.javatip.common.utils.RunPythonScript;
import com.javatip.common.utils.Utils;
import com.javatip.common.utils.file.FileUtils;
import com.javatip.project.deep_learning.app01Dataset.domain.App01Dataset;
import com.javatip.project.deep_learning.app01Dataset.service.App01DatasetServiceImpl;
import com.javatip.project.deep_learning.trainMission.controller.TrainMissionController;
import com.javatip.project.deep_learning.trainMission.domain.TrainMission;
import com.javatip.project.deep_learning.trainMission.service.TrainMissionServiceImpl;
import com.javatip.project.detection.detectionDataset.service.DetectionDatasetServiceImpl;
import com.javatip.project.queue.domain.Task;
import com.javatip.project.queue.service.QueueService;
import com.javatip.project.system.user.domain.User;
import com.javatip.project.system.user.service.IUserService;
import io.swagger.annotations.Api;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.util.ThreadContext;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import com.javatip.project.deep_learning.predict.domain.Predict;
import com.javatip.project.deep_learning.predict.service.IPredictService;
import com.javatip.framework.web.controller.BaseController;
import com.javatip.framework.web.page.TableDataInfo;
import com.javatip.framework.web.domain.AjaxResult;

/**
 * 识别信息操作处理
 *
 * @author 袁伟
 * @date 2024-07-24
 */
@Api(tags = "语义分割推理结果管理")
@Controller
@RequestMapping("/deep_learning/predict")
public class PredictController extends BaseController {
    @Autowired
    private QueueService queueService;

    private String prefix = "deep_learning/predict";

    @Autowired
    private IPredictService predictService;
    @Autowired
    private TrainMissionServiceImpl trainMissionServiceImpl;
    @Autowired
    private IUserService userService;
    @Autowired
    private DetectionDatasetServiceImpl detectionDatasetServiceImpl;
    @Autowired
    private App01DatasetServiceImpl app01DatasetServiceImpl;

    @RequiresPermissions("deep_learning:predict:view")
    @GetMapping()
    public String predict() {
        return prefix + "/predict";
    }


    // 每 10 秒调用一次 doPredict 方法
//    @Scheduled(fixedRate = 10000)
    public void scheduledDoPredict() {
//        System.out.println("scheduledDoPredict()");
        try {
            DefaultWebSecurityManager manager = new DefaultWebSecurityManager();
            ThreadContext.bind(manager);
            doPredict();
        } catch (Exception e) {
            System.out.println("出错");
        }
    }

    /**
     * 查询识别列表，只显示与当前id相同的识别任务
     */
    @RequiresPermissions("deep_learning:predict:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(Predict predict) {
        startPage();
        User currentUser = getSysUser();
        int currentUserId = Integer.parseInt(String.valueOf(currentUser.getUserId()));
        System.out.println("当前用户id:"+currentUserId);
        List<Predict> list = predictService.selectPredictListWithSameUserId(currentUserId,predict);
//		与当前id相同的识别任务
        System.out.println("list："+list);
        //        添加用户名
        for (Predict m : list) {
            String userName = userService.getUsernameByUserId(Long.valueOf(m.getUserId()));
            m.setUserName(userName);
        }
//        System.out.println(list1);
        return getDataTable(list);
    }

    /*
     * admin用户获取所有识别列表
     */
    @RequiresPermissions("deep_learning:predict:list")
    @PostMapping("/listAdmin")
    @ResponseBody
    public TableDataInfo listAdmin(Predict predict) {
        startPage();
        List<Predict> list = predictService.selectPredictList(predict);
        //        添加用户名
        for (Predict m : list) {
            String userName = userService.getUsernameByUserId(Long.valueOf(m.getUserId()));
            m.setUserName(userName);
            //设置数据集的归属用户
            App01Dataset dataSet=app01DatasetServiceImpl.selectApp01DatasetById(m.getDatasetId());
            m.setDatasetName(m.getDatasetName()+"："+userService.getUsernameByUserId(dataSet.getUserId().longValue()));
            //设置训练任务的归属用户
            m.setTrainMissionName(m.getTrainMissionName()+"："+userService.getUsernameByUserId(trainMissionServiceImpl.selectTrainMissionById(m.getTrainMissionId()).getUserId().longValue()));
        }
        return getDataTable(list);
    }

    /**
     * 新增识别
     */
    @GetMapping("/add")
    public String add() {
        return prefix + "/add";
    }

    /**
     * 新增保存识别
     */
    @RequiresPermissions("deep_learning:predict:add")
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(Predict predict) {

//        System.out.println("插入的predict"+predict);
        return toAjax(predictService.insertPredict(predict));
    }

    /**
     * 修改识别
     */
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") Integer id, ModelMap mmap) {
        Predict predict = predictService.selectPredictById(id);
        mmap.put("predict", predict);
        return prefix + "/edit";
    }

    /**
     * 修改保存识别
     */
    @RequiresPermissions("deep_learning:predict:edit")
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(Predict predict) {
        return toAjax(predictService.updatePredict(predict));
    }

    /**
     * 删除识别
     */
    @RequiresPermissions("deep_learning:predict:remove")
    @PostMapping("/remove")
    @ResponseBody
    public AjaxResult remove(String ids) {
        return toAjax(predictService.deletePredictByIds(ids));
    }

    /**
     * 开始识别，接收识别id
     */
    @GetMapping("/doSingleInference/{id}")
    @ResponseBody
    public ResponseEntity<String> doSingleInference(@PathVariable("id") Integer id) {
        int result = predictService.predict(id);
        if (result == 0) {
            //压入队列=================
            Task task= new Task(predictService.selectPredictById(id).getPredictName(),"segPredict",id, new Timestamp(System.currentTimeMillis()));
            String res=queueService.saveTask(task);

            return ResponseEntity.ok("Training started successfully for id: " + id);
        } else {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Failed to start training for id: " + id);
        }
    }

    /**
     * 停止识别
     */
    @GetMapping("/stopSingleInference/{id}")
    @ResponseBody
    public ResponseEntity<String> stopSingleInference(@PathVariable("id") Integer id) {
        boolean result = predictService.stopSingePredict(id);
        System.out.println("stopSingePredict result: " + result);
        if (result) {
            //删除队列
            queueService.deleteTaskByTypeAndID("segPredict", id);

            System.out.println("Predicting stopped successfully for id: " + id);
            return ResponseEntity.ok("Predicting stopped successfully for id: " + id);
        } else {
            System.out.println("Failed to stop predicting for id: " + id);
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Failed to stop predicting for id: " + id);
        }
    }


    /**
     * 获取识别任务的status
     */
    @GetMapping("/getStatus/{id}")
    @ResponseBody
    public ResponseEntity<String> getInferenceStatus(@PathVariable("id") Integer id) {
        System.out.println("getInferenceStatusID:"+id);
        String status = predictService.getInferenceStatus(id);
        System.out.println("status:"+status);
//		status转为json格式
        status = "{\"status\":\"" + status + "\"}";

        if (status == null) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Inference task not found for id: " + id);
        }
        return ResponseEntity.ok(status);
    }

    //	处理delete删除请求
    @PostMapping("/delete/{id}")
    @ResponseBody
    public ResponseEntity<String> delete(@PathVariable("id") Integer id) {
        int result = predictService.deletePredictById(id);
        if (result == 1) {
            return ResponseEntity.ok("删除成功 " + id);
        } else {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("删除失败: " + id);
        }

    }

    /**
     * 返回识别图片列表
     * {
     * "imagePaths": [
     * "/images/img1.jpg",
     * "/images/img2.jpg",
     * "/images/img3.jpg",
     * ...
     * ]
     * }
     */
    @GetMapping("/getImages/{id}")
    @ResponseBody
    public ResponseEntity<List<String>> getImages(@PathVariable("id") Integer id) {
        // 获取当前路径
        String currentPath = System.getProperty("user.dir").toString().replace("\\","/");
        // 获取图片路径
        String imagePath = currentPath + "/src/main/resources/predictResult/"
                + predictService.selectPredictById(id).getUserId() + "/"
                + predictService.selectPredictById(id).getTrainMissionId() + "/"
                + predictService.selectPredictById(id).getDatasetId() + "/compareResult/";

        System.out.println("imagePath: " + imagePath);
        File directory = new File(imagePath);
        File[] files = directory.listFiles((dir, name) -> name.toLowerCase().endsWith(".jpg") ||
                name.toLowerCase().endsWith(".png")); // 根据需要添加其他图片格式

        System.out.println("files: " + files);
        List<String> imagePaths = new ArrayList<>();

        if (files != null) {
            for (File file : files) {
                String relativePath = "/predictResult/" + predictService.selectPredictById(id).getUserId() + "/"
                        + predictService.selectPredictById(id).getTrainMissionId() + "/"
                        + predictService.selectPredictById(id).getDatasetId() + "/compareResult/"
                        + file.getName();
                imagePaths.add(relativePath);
            }
        }

        System.out.println("imagePaths: " + imagePaths);
        return new ResponseEntity<>(imagePaths, HttpStatus.OK);
    }


    /**
     * 修改识别任务的status为待识别
     *
     * @param id
     * @return
     */
    @GetMapping("/updateStatusToWait/{id}")
    public ResponseEntity<String> updateStatusToWait(@PathVariable("id") int id) {
        System.out.println("updateStatusToWait");
        int result = predictService.updateStatusToWait(id);
        // 在数据库表中更新识别任务的加入队列时间
        predictService.setTimeToQueue(id);
        if (result == 1) {
            //压入队列=================
            Task task= new Task(predictService.selectPredictById(id).getPredictName(),"segPredict",id, new Timestamp(System.currentTimeMillis()));
            String res=queueService.saveTask(task);

            return ResponseEntity.ok("Status updated successfully for id: " + id);
        } else {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Failed to update status for id: " + id);
        }
    }


    /**
     * 修改识别任务的status为未识别
     *
     * @param id
     * @return
     */
    @GetMapping("/updateStatusToNotPredict/{id}")
    public ResponseEntity<String> updateStatusToNotPredict(@PathVariable("id") int id) {
        System.out.println("updateStatusToNotTrain");
        int result = predictService.updateStatusToNotPredict(id);
        // 在数据库表中更新识别任务的加入队列时间为null
//        predictService.setTimeToQueueNull(id);
        if (result == 1) {
            //删除队列
            queueService.deleteTaskByTypeAndID("segPredict", id);
            return ResponseEntity.ok("Status updated successfully for id: " + id);
        } else {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Failed to update status for id: " + id);
        }
    }


    // 定义一个标准化的错误响应类
    static class ErrorResponse {
        private String message;

        public ErrorResponse(String message) {
            this.message = message;
        }

        public String getMessage() {
            return message;
        }

        public void setMessage(String message) {
            this.message = message;
        }
    }

    /**
     * 训练列表里逐个训练
     *
     * @return
     */
    @GetMapping("doPredict")
//	@ResponseBody
    public ResponseEntity<?> doPredict() {

//		System.out.println("Controller-doPredict");

        try {
            int result = predictService.doPredict(); // 获取结果

            if (result == 0) {
                // 成功的情况，返回 200 OK 和结果
                return ResponseEntity.ok().body("训练成功");
            } else {
                // 失败的情况，返回 400 错误响应
                System.out.println("Controller-未正常结束");
                return ResponseEntity.badRequest().body(new PredictController.ErrorResponse("训练失败，请检查输入或稍后重试。"));
            }
        } catch (Exception e) {
            // 捕获并处理所有异常，返回自定义错误响应
            String errorMessage = "执行Python脚本时发生错误：" + e.getMessage();
            System.err.println(errorMessage);
            e.printStackTrace(); // 打印堆栈信息，帮助调试
            return ResponseEntity.badRequest().body(new PredictController.ErrorResponse(errorMessage));
        }
    }

    @GetMapping("stopPredict")
//	@ResponseBody
    public ResponseEntity<?> stopPredict() {

        System.out.println("Controller-stopTraining");

        try {
            int result = predictService.stopPredict(); // 获取结果

            if (result == 0) {
                // 成功的情况，返回 200 OK 和结果
                return ResponseEntity.ok().body("训练成功");
            } else {
                // 失败的情况，返回 400 错误响应
                System.out.println("Controller-未正常结束");
                return ResponseEntity.badRequest().body(new PredictController.ErrorResponse("训练失败，请检查输入或稍后重试。"));
            }
        } catch (Exception e) {
            // 捕获并处理所有异常，返回自定义错误响应
            String errorMessage = "执行Python脚本时发生错误：" + e.getMessage();
            System.err.println(errorMessage);
            e.printStackTrace(); // 打印堆栈信息，帮助调试
            return ResponseEntity.badRequest().body(new PredictController.ErrorResponse(errorMessage));
        }
    }


    @GetMapping("/getWaitAndPredictList")
    @ResponseBody
//	返回数组
    public List<Predict> getWaitAndPredictList() {
        List<Predict> list = predictService.selectPredictList(null);
        // 筛选出待识别和识别中的任务
        List<Predict> resultList = new ArrayList<>();
        for (Predict predict : list) {
            if (predict.getStatus().equals("待识别") || predict.getStatus().equals("识别中")) {
                resultList.add(predict);
            }
        }
        return resultList;
    }

    /**
     * 获取识别所用模型,方法名为downloadInferenceResult，返回的是json格式的文件地址，fileUrl是下载地址
     */

    @GetMapping("/downloadInferenceResult/{id}")
    @ResponseBody
    public ResponseEntity<byte[]> downloadInferenceResult(@PathVariable("id") Integer id) {
        Predict predict = predictService.selectPredictById(id);
        int trainMissionid = predict.getTrainMissionId();
        int datasetid = predict.getDatasetId();
//        获取当前路径
        String currentPath = System.getProperty("user.dir").toString().replace("\\","/");
        // 获取文件路径
        String filePath = currentPath + "/src/main/resources/trainResult/" + trainMissionid + "/predictResult/";
        System.out.println("filePath: " + filePath);
//        获取路径下的pth文件
        File directory = new File(filePath);
        File[] files = directory.listFiles((dir, name) -> name.toLowerCase().endsWith(".pth"));
        System.out.println("files: " + files);
        String pthFile = "";
        for (File file : files) {
            pthFile = file.getName();
        }
        String fileUrl = "/" + trainMissionid + "/predictResult/" + pthFile;
        System.out.println("fileUrl: " + fileUrl);
//        转为json格式
        String result = "{\"fileUrl\":\"" + fileUrl + "\"}";
        return ResponseEntity.ok().body(result.getBytes());
    }

    /**
     * 获取识别所用模型,方法名为downloadInferenceResultZip，返回的是json格式的文件地址，fileUrl是下载地址
     */
    @GetMapping("/downloadInferenceResultZip/{id}")
    @ResponseBody
    public ResponseEntity<String> downloadInferenceResultZip(@PathVariable("id") Integer id) {
        Predict predict = predictService.selectPredictById(id);
        int trainMissionid = predict.getTrainMissionId();
        int datasetid = predict.getDatasetId();

        // 获取当前路径
        String currentPath = System.getProperty("user.dir").toString().replace("\\","/");

        // 推理文件夹路径
        String inferencePath = currentPath + "/src/main/resources/predictResult/" + predict.getUserId() + '/' + trainMissionid + "/" + datasetid;

        // 获取文件路径
        String filePath = currentPath + "/src/main/resources/predictResult/" + predict.getUserId() + '/' + trainMissionid + "/" + datasetid + "/predictResult/";
        String fileComparePath = currentPath + "/src/main/resources/predictResult/" + predict.getUserId() + '/' + trainMissionid + "/" + datasetid + "/compareResult/";

//
//        Integer selectedDatasetId = predict.getDatasetId();
//        Integer datasetUserId = app01DatasetServiceImpl.selectApp01DatasetById(selectedDatasetId).getUserId();// 获取数据集归属者id
//        String datasetPath = currentPath + "/src/main/resources/datasets/" + datasetUserId + "/" +
//                app01DatasetServiceImpl.selectApp01DatasetById(selectedDatasetId).getName() + "/";
//        // 检测datasetPath下是否有名为tif的文件夹
//        // 构建tif文件夹的路径
//        String tifFolderPath = datasetPath + "tif";
//        // 检查tif文件夹是否存在
//        File tifFolder = new File(tifFolderPath);
//        System.out.println("tif文件夹路径：" + tifFolderPath);
//        boolean tifFolderExist = tifFolder.exists() && tifFolder.isDirectory();
//        // 如果tif文件夹存在，执行Python脚本
//        if (tifFolderExist) {
//            System.out.println("The 'tif' folder exists. Proceeding with processing...");
//
//            // 输入、输出路径
//            String pngInputPath = filePath; // 输入PNG文件路径
//            String tifInputPath = datasetPath + "tif/";
//            String shapefileOutputPath = filePath + "../shp/"; // 输出Shapefile路径
//            // 创建shp文件夹
//            File shpFolder = new File(shapefileOutputPath);
//            System.out.println("shp 文件夹路径：" + shapefileOutputPath);
//            if (!shpFolder.exists()) {
//                shpFolder.mkdirs();
//            }
//
//            // 构建Python脚本路径
//            String pythonScriptPath = currentPath + "/src/main/resources/CorsicanFire/utils/批量轮廓提取V2.py";
//
////            System.out.println("pythonScriptPath: "+pythonScriptPath);
////            System.out.println("pngInputPath: "+pngInputPath);
////            System.out.println("tifOutputPath: "+tifInputPath);
//
//            // 调用Python脚本执行处理任务
//            RunPythonScript.runPythonScriptWithGeoArgs(pythonScriptPath, pngInputPath, tifInputPath, shapefileOutputPath);
//        } else {
//            System.out.println("The 'tif' folder does not exist in the dataset path.");
//        }


        // 创建ZIP文件路径
        String zipFilePath = currentPath + "/src/main/resources/predictResult/" + predict.getUserId() +
                '/' + trainMissionid + "/" + datasetid + "/" + predict.getDatasetName() + ".zip";


        // 检测inferencePath下是否有jsonOutput文件夹
        boolean exist = FileUtils.isExist(inferencePath + "/jsonOutput");
        System.out.println("是否存在jsonOutput文件夹：" + exist);
        if (exist) {
            // 压缩文件夹
            System.out.println("存在jsonOutput文件夹，开始压缩文件夹");
            boolean compressed = FileUtils.compressFolder(inferencePath + "/jsonOutput", zipFilePath);

            if (compressed) {
                // 创建文件下载链接
                String fileUrl = "/predictResult/" + predict.getUserId() + '/'
                        + trainMissionid + "/" + datasetid + "/" + predict.getDatasetName() + ".zip";

                // 返回包含文件URL的JSON响应
                String result = "{\"fileUrl\":\"" + fileUrl + "\"}";
                return ResponseEntity.ok()
                        .contentType(MediaType.APPLICATION_JSON)
                        .body(result);
            } else {
                // 压缩失败的处理逻辑

                return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                        .body("{\"error\":\"压缩文件夹失败\"}");
            }
        } else {
            try {
                // 压缩文件夹
                System.out.println("不存在jsonOutput文件夹，开始压缩文件夹");
                zipFilesWithFolders(filePath, fileComparePath, zipFilePath);


                // 创建文件下载链接
                String fileUrl = "/predictResult/" + predict.getUserId() + '/' + trainMissionid + "/" +
                        datasetid + "/" + predict.getDatasetName() + ".zip";

                // 返回包含文件URL的JSON响应
                String result = "{\"fileUrl\":\"" + fileUrl + "\"}";
                return ResponseEntity.ok()
                        .contentType(MediaType.APPLICATION_JSON)
                        .body(result);
            } catch (IOException e) {
                e.printStackTrace();
                return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
            }
        }
    }

    private void zipFilesWithFolders(String filePath, String fileComparePath, String zipFilePath) throws IOException {

        try (
                FileOutputStream fos = new FileOutputStream(zipFilePath);
                ZipOutputStream zos = new ZipOutputStream(fos)

        ) {
            // 判断是否有tif和shp文件夹
            String tifFolderPath = filePath + "../tif/";
            String shpFolderPath = filePath + "../shp/";
            File tifFolder = new File(tifFolderPath);
            File shpFolder = new File(shpFolderPath);
            if (tifFolder.exists() && tifFolder.isDirectory() && shpFolder.exists() && shpFolder.isDirectory()) {
                // 压缩 tifFolderPath 路径下的文件到 tif 文件夹
                Path sourceTifPath = Paths.get(tifFolderPath);
                Files.walk(sourceTifPath).filter(path -> !Files.isDirectory(path)).forEach(path -> {
                    ZipEntry zipEntry = new ZipEntry("tif/" + sourceTifPath.relativize(path).toString());
                    try {
                        zos.putNextEntry(zipEntry);
                        Files.copy(path, zos);
                        zos.closeEntry();
                    } catch (IOException e) {
                        System.err.println("Failed to add file to ZIP: " + path);
                        e.printStackTrace();
                    }
                });
                // 压缩 shpFolderPath 路径下的文件到 shp 文件夹
                Path sourceShpPath = Paths.get(shpFolderPath);
                Files.walk(sourceShpPath).filter(path -> !Files.isDirectory(path)).forEach(path -> {
                    ZipEntry zipEntry = new ZipEntry("shp/" + sourceShpPath.relativize(path).toString());
                    try {
                        zos.putNextEntry(zipEntry);
                        Files.copy(path, zos);
                        zos.closeEntry();
                    } catch (IOException e) {
                        System.err.println("Failed to add file to ZIP: " + path);
                        e.printStackTrace();
                    }
                });
            } else {
                // 压缩 filePath 路径下的文件到 predictResult 文件夹
                Path sourcePath = Paths.get(filePath);
                Files.walk(sourcePath).filter(path -> !Files.isDirectory(path)).forEach(path -> {
                    ZipEntry zipEntry = new ZipEntry("predictResult/" + sourcePath.relativize(path).toString());
                    try {
                        zos.putNextEntry(zipEntry);
                        Files.copy(path, zos);
                        zos.closeEntry();
                    } catch (IOException e) {
                        System.err.println("Failed to add file to ZIP: " + path);
                        e.printStackTrace();
                    }
                });
            }


            /*
            压缩 fileComparePath 路径下的文件到 compareResult 文件夹
             */
//            Path sourceComparePath = Paths.get(fileComparePath);
//            Files.walk(sourceComparePath).filter(path -> !Files.isDirectory(path)).forEach(path -> {
//                ZipEntry zipEntry = new ZipEntry("compareResult/" + sourceComparePath.relativize(path).toString());
//                try {
//                    zos.putNextEntry(zipEntry);
//                    Files.copy(path, zos);
//                    zos.closeEntry();
//                } catch (IOException e) {
//                    System.err.println("Failed to add file to ZIP: " + path);
//                    e.printStackTrace();
//                }
//            });

        }
    }


    /**
     * 获取进度条数据，getProgress+id
     */
    @GetMapping("/getProgress/{id}")
    @ResponseBody
    public Map<String, Object> getProgress(@PathVariable("id") int id) {
//        System.out.println("getProgress");
//        System.out.println("predict id: "+id);
        Map<String, Object> response = new HashMap<>();
        Predict predictMission = predictService.selectPredictById(id);
        if (predictMission != null) {
            response.put("status", "success");
            // 获取当前路径
            String currentPath = System.getProperty("user.dir");
            String parentParentPath = Utils.getParentPath(currentPath, 0);
            currentPath = parentParentPath + "/src/main/resources/predictResult/" + predictMission.getUserId()
                    + "/" + predictMission.getTrainMissionId() + "/" + predictMission.getDatasetId() + "/";
//            System.out.println("currentPath: " + currentPath);

            // 读取 currentPath 下面的progress.txt 文件，如果不存在，则返回空数据
            String content = "";
            String tifConetent = "";
            boolean tif_exist = false;

            try {
                content = new String(Files.readAllBytes(Paths.get(currentPath + "progress.txt")));
            } catch (IOException e) {
//                e.printStackTrace();
                response.put("status", "success");
                response.put("data", 0);
//                System.out.println("txt文件不存在");
                response.put("message", "未开始训练");
                return response;
            }
            try {
                tifConetent = new String(Files.readAllBytes(Paths.get(currentPath+"progress_tif.txt")));
                tif_exist = true;
            } catch (IOException e) {
//                System.out.println("不存在tif进度文件");
            }

            // 解析内容，读取最后一行Progress: 后面的数字，是两位小数的进度百分比,去掉%符号
            String[] lines = content.split("\n");
            String lastLine = lines[lines.length - 1];

            String[] tif_lines = null;
            String tif_lastLine= null;

            if (tif_exist){
                tif_lines=tifConetent.split("\n");
                tif_lastLine = tif_lines[tif_lines.length-1];
            }

            if (lastLine.startsWith("Progress: ")) {
                String progressStr = lastLine.substring("Progress: ".length());
                progressStr = progressStr.replace("%", "");
                double progress = Double.parseDouble(progressStr);

//                System.out.println("progress: " + progress);


                if (progress >= 100 && tif_exist==false) {
//                    System.out.println("没有tif进度，训练完成");
                    response.put("data",100);
                    response.put("finish", "finish");
                }else if(progress<100){
//                    System.out.println("progress："+progress);
                    response.put("data", progress);
                }else {
//                    System.out.println("tif进度"+tifConetent);
                        String tif_progressStr = tif_lastLine.substring("Progress: ".length());
                        tif_progressStr=tif_progressStr.replace("%", "");
                        double tif_progress = Double.parseDouble(tif_progressStr);
                        response.put("data",tif_progress);

                }
                response.put("message", "获取进度条数据成功");
                return response;
            } else {
                response.put("status", "success");
                response.put("data", 0);
                response.put("message", "未开始训练");
                return response;
            }
        } else {
            response.put("status", "error");
            response.put("message", "获取进度条数据失败");
            return response;
        }
    }

    /**
     * 检查任务名称是否存在
     *
     * @param name
     * @return
     */
    @GetMapping("/checkTrainMissionName")
    @ResponseBody
    public ResponseEntity<Boolean> checkTrainMissionName(@RequestParam("name") String name) {
        int userId = getSysUser().getUserId().intValue();
        boolean exists = predictService.isPredictNameExists(name, userId); // 该方法检查任务名称是否存在
        return ResponseEntity.ok(exists);
    }


    /**
     * 检查任务先前是否存在
     *
     * @param
     * @return
     */
    @GetMapping("/checkPredictMissionUnique")
    @ResponseBody
    public ResponseEntity<Boolean> checkPredictMissionUnique(@RequestParam("trainMissionId") int trainMissionId,
                                                             @RequestParam("datasetId") int datasetId,
                                                             @RequestParam("user_id") int userId) {

//        System.out.println("checkPredictMissionUnique");
//        System.out.println("trainMissionId: " + trainMissionId);
//        System.out.println("datasetId: " + datasetId);
//        System.out.println("userId: " + userId);
        boolean exists = predictService.isPredictMissionUnique(trainMissionId, datasetId, userId); // 该方法检查先前是否存在
        return ResponseEntity.ok(exists);
//        return null;
    }

    /**
     * 获取队列位次
     */
    @GetMapping("/getQueuePosition/{id}")
    public ResponseEntity<Map<String, Object>> getQueuePosition(@PathVariable("id") Integer id) {
//        System.out.println("getQueuePosition");

        Integer postion =queueService.getTimePositionByTaskID(id,"segPredict");
        Map<String, Object> response = new HashMap<>();


        if (postion != null) {

            response.put("queuePosition", postion);

        } else {
            response.put("queuePosition", null);
        }

        return ResponseEntity.ok(response);
    }
}
